package cn.sail.shiroAuthenticator.main;

import cn.sail.shiroAuthenticator.security.CustomRealm;
import cn.sail.shiroAuthenticator.security.CustomRealmWithMD5;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

public class ShiroWithIniRealmByCredentialsMatcherTest {
    public static void main(String[] args) {
        //创建安全管理器
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //自定义Realm进行用户校验
        CustomRealmWithMD5 customRealmWithMD5 = new CustomRealmWithMD5();
        //设置密码匹配规则器
        customRealmWithMD5.setCredentialsMatcher(hashedCredentialsMatcher());
        defaultSecurityManager.setRealm(customRealmWithMD5);
        //安全管理器设置到运行环境仲
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        //获取当前操作的主体
        Subject subject = SecurityUtils.getSubject();
        //创建token
        UsernamePasswordToken yxjToken = new UsernamePasswordToken("yxj", "123456789");
        //传递token进行校验
        subject.login(yxjToken);
        //这里的校验是去shiro的内部进行校验
        System.out.println("用户的认证状态"+subject.isAuthenticated());

    }

    /**
     * 返回密码规则
     * @return
     */
    public static HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //这里就是设置散列的方法的地方
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //设置的是散列的次数
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
    }
}